package com.huiketong.cofpasgers.controller;

import com.alipay.api.AlipayApiException;
import com.huiketong.cofpasgers.constant.Constant;
import com.huiketong.cofpasgers.constant.URL;
import com.huiketong.cofpasgers.entity.*;
import com.huiketong.cofpasgers.json.data.ShareTypeData;
import com.huiketong.cofpasgers.json.data.VoucherShareData;
import com.huiketong.cofpasgers.json.data.WholeDesignDetailData;
import com.huiketong.cofpasgers.json.layuidata.DesignCaseResp;
import com.huiketong.cofpasgers.json.layuidata.LinShareResp;
import com.huiketong.cofpasgers.json.layuidata.ShareTypeResp;
import com.huiketong.cofpasgers.json.response.BaseJsonResponse;
import com.huiketong.cofpasgers.repository.*;
import com.huiketong.cofpasgers.service.IDemand;
import com.huiketong.cofpasgers.util.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class LinShareController {

    @Autowired
    LinShareRepository linShareRepository;
    @Autowired
    DefaultEnterRepository defaultEnterRepository;
    @Autowired
    AgentRepository agentRepository;
    @Autowired
    EnterpriseRepository enterpriseRepository;
    @Autowired
    WestingHouseRepository westingHouseRepository;
    @Autowired
    WareHousesRepository wareHousesRepository;
    @Autowired
    DesignCaseRepository designCaseRepository;
    @Autowired
    ShareTypeRepository shareTypeRepository;
    @Autowired
    RoomPolysRepository roomPolysRepository;

    @GetMapping("linshare")
    public String linShare(){
        return URL.LINSHARE;
    }
    @GetMapping("linsharecontent")
    public String linShareContent(){
        return URL.LINSHARECONTENT;
    }
    @GetMapping("westinghouse")
    public String westingHouse(){
        return URL.WESTINGHOUSE;
    }

    @GetMapping("back_designcase")
    public String backDesignCase(){
        return URL.BACKDESIGNCASE;
    }

    @GetMapping("warehouses")
    public String wareHouses(){
        return URL.WAREHOUSES;
    }
    @GetMapping("roompolys")
    public String roompolys(){
        return URL.ROOMPOLYS;
    }
    @GetMapping("wholedesign")
    public String wholeDesign(){
        return URL.WHOLEDESIGNCASEMANAGE;
    }

    @GetMapping("designcase")
    public String designCase(){
        return URL.DESIGNCASE;
    }

    @GetMapping("sharetypemanager")
    public String shareTypeManager(){
        return URL.SHARETYPEMANAGER;
    }

    @GetMapping("addsharetype")
    public String addShareType(){
        return URL.ADDSHARETYPE;
    }

    @GetMapping("editsharetype")
    public ModelAndView editShareType(Integer id){
        ShareType shareType = shareTypeRepository.findShareTypeById(id);
        ModelAndView mv = new ModelAndView();
        if(!ObjectUtils.isEmpty(shareType)){
            mv.addObject("title",shareType.getTitle());
            mv.addObject("url",shareType.getUrl());
            mv.addObject("imgurl",shareType.getImgUrl());
            mv.addObject("sharetype",shareType.getType());
        }
        mv.setViewName(URL.EDITSHARETYPE);
        return mv;
    }

    @GetMapping("edit_linshare_content")
    public ModelAndView editLinshareContent(Integer id){
        LinShare linShare = linShareRepository.findLinShareById(id);
        ModelAndView mv = new ModelAndView();
        if(!ObjectUtils.isEmpty(linShare)) {
            mv.addObject("title", linShare.getTitle());
            mv.addObject("content",linShare.getContent());
            mv.addObject("url",linShare.getUrl());
            mv.addObject("sharetype",linShare.getType());
            mv.addObject("topimg",linShare.getTopimg());
            mv.addObject("bottomimg",linShare.getBottomimg());
            mv.addObject("bgcolor",linShare.getBackgroud());
        }
        mv.setViewName(URL.EDITLINSHARECONTENT);
        return mv;
    }

    @GetMapping("edit_whole_design_case")
    public ModelAndView editWholeDesignCase(Integer id){
        ModelAndView mv = new ModelAndView();
        DesignCase designCase = designCaseRepository.findDesignCaseById(id);
        if(!ObjectUtils.isEmpty(designCase)){
            mv.addObject("title",designCase.getTitle());
            mv.addObject("subtitle",designCase.getSubtitle());
            mv.addObject("content",designCase.getContent());
            mv.addObject("mainimg",designCase.getImage());
            mv.addObject("style",designCase.getStyle());
        }
        mv.setViewName(URL.EDITWHOLEDESIGNCASE);
        return mv;
    }

    @GetMapping("/back/sharetypelist")
    @ResponseBody
    public ShareTypeResp shareTypeList(String user_id){
        ShareTypeResp resp = new ShareTypeResp();
        Enterprise enterprise = enterpriseRepository.findEnterpriseByEnterLoginName(user_id);
        List<ShareType> shareTypeList = shareTypeRepository.findShareTypesByCompanyIdOrderBySort(enterprise.getId());
        if(shareTypeList.size() > 0){
            List<ShareTypeResp.DataBean> dataBeanList = new ArrayList<>();
            for(ShareType shareType:shareTypeList){
                ShareTypeResp.DataBean dataBean = new ShareTypeResp.DataBean();
                dataBean.setId(shareType.getId());
                dataBean.setTitle(shareType.getTitle());
                dataBean.setImg(shareType.getImgUrl());
                dataBeanList.add(dataBean);
            }
            resp.setData(dataBeanList);
            resp.setCode(0);
            resp.setCount(String.valueOf(shareTypeList.size()));
            resp.setMsg("");
        }else{
            resp.setData(new ArrayList<>());
            resp.setCode(0);
            resp.setCount("");
            resp.setMsg("");
        }
        return resp;
    }

    @PostMapping("/back/del_sharetype")
    @ResponseBody
    public BaseJsonResponse delShareType(Integer id){
        BaseJsonResponse response = new BaseJsonResponse();
        try {
            shareTypeRepository.deleteById(id);
            response.setCode("0").setMsg("删除成功");
        }catch (Exception e){
            response.setCode("1").setMsg("删除失败");
        }


        return response;
    }

    /**
     * 2019年11月14号
     * 获客分享
     * @return
     */
    @PostMapping(value = "/api/linshare")
    @ResponseBody
    @CrossOrigin
    public Object linShare(String user_id, String token, Integer sharetype) throws ParseException, AlipayApiException {
        BaseJsonResponse response = new BaseJsonResponse();
        verifyUser(user_id, token, response, o -> {
            Agent agent = (Agent) o;
            LinShare linShare = linShareRepository.findLinShareByTypeAndCompanyId(sharetype,agent.getCompanyId());
            if(!ObjectUtils.isEmpty(linShare)){
                VoucherShareData voucherShareData = new VoucherShareData();
                voucherShareData.setContext(linShare.getContent());
                voucherShareData.setImage(linShare.getImgUrl());
                voucherShareData.setLink_url(Constant.URL+linShare.getUrl()+"?userId="+agent.getId()+"&companyId="+agent.getCompanyId());
                voucherShareData.setTitle(linShare.getTitle());
                voucherShareData.setUser_id(agent.getId());
                voucherShareData.setTopimg(linShare.getTopimg());
                voucherShareData.setBottomImg(linShare.getBottomimg());
                voucherShareData.setBackground(linShare.getBackgroud());
                voucherShareData.setCompany_id(agent.getCompanyId());
                voucherShareData.setNum(linShare.getNum());
                response.setCode("1").setMsg("分享成功").setData(voucherShareData);
            }else{
                response.setCode("100").setMsg("没有该类型的分享");
            }

        });
        return response;
    }

    @PostMapping(value = "/api/wholeshare")
    @ResponseBody
    @CrossOrigin
    public Object wholeShare(Integer userId,Integer id){
        BaseJsonResponse response = new BaseJsonResponse();
        return response;
    }

    @PostMapping("/api/add_sharetype")
    @ResponseBody
    @CrossOrigin
    public Object addShareTypeManager(String userId,String title,String imgurl,Integer sharetype,String url){
        BaseJsonResponse response = new BaseJsonResponse();

        Enterprise enterprise = enterpriseRepository.findEnterpriseByEnterLoginName(userId);
        if(!ObjectUtils.isEmpty(enterprise)){
            ShareType existShareType = shareTypeRepository.findShareTypeByCompanyIdAndAndType(enterprise.getId(),sharetype);
            if(ObjectUtils.isEmpty(existShareType)) {
                ShareType shareType = new ShareType();
                shareType.setCompanyId(enterprise.getId());
                shareType.setImgUrl(imgurl);
                shareType.setUrl(url);
                shareType.setTitle(title);
                shareType.setType(sharetype);
                shareTypeRepository.save(shareType);
                response.setCode("0").setMsg("添加成功");
            }else{
                response.setCode("200").setMsg("已存在相同类型");
            }

        }else{
            response.setCode("0").setMsg("添加失败");
        }
        return response;
    }

    @PostMapping(value = "/api/edit_sharetype")
    @ResponseBody
    public BaseJsonResponse editShareType(Integer id,String title,String imgurl,Integer sharetype,String url){
        BaseJsonResponse response = new BaseJsonResponse();
        ShareType shareType = shareTypeRepository.findShareTypeById(id);
        if(!ObjectUtils.isEmpty(shareType)){
            try {
                shareTypeRepository.updateShareType(title,imgurl,shareType,url,id);
            }catch (Exception e){
                response.setMsg("修改失败").setCode("300");
            }
           response.setMsg("修改成功").setCode("0");
        }
        return response;
    }


    @GetMapping("/api/getLinshareList")
    @ResponseBody
    public LinShareResp getLinshareList(String user_id){
        LinShareResp resp = new LinShareResp();
        Enterprise enterprise = enterpriseRepository.findEnterpriseByEnterLoginName(user_id);
        if(!ObjectUtils.isEmpty(enterprise)){
            List<LinShare> linShareList = linShareRepository.findLinSharesByCompanyId(enterprise.getId());
            if(linShareList.size() > 0){
                resp.setCode(0);
                resp.setCount(String.valueOf(linShareList.size()));
                List<LinShareResp.DataBean> dataBeanList = new ArrayList<>();
                for(LinShare linShare:linShareList){
                    LinShareResp.DataBean dataBean = new LinShareResp.DataBean();
                    dataBean.setId(linShare.getId());
                    dataBean.setContext(linShare.getContent());
                    dataBean.setImage(linShare.getImgUrl());
                    dataBean.setLink_url(linShare.getUrl());
                    dataBean.setSharetype(linShare.getType());
                    dataBean.setTitle(linShare.getTitle());
                    dataBeanList.add(dataBean);
                }
                resp.setData(dataBeanList);
                resp.setMsg("");
            }
        }else{
            resp.setMsg("");
            resp.setData(new ArrayList<>());
            resp.setCode(0);
            resp.setCount("0");
        }
        return resp;
    }


    @PostMapping("/api/add_linsharecontent")
    @ResponseBody
    public Object addLinShareContent(Integer id,String userId,String title,String url,String imgUrl,String upimg,String downimg,String bgcolor,Integer sharetype,String content){
        BaseJsonResponse response = new BaseJsonResponse();
        Enterprise enterprise = enterpriseRepository.findEnterpriseByEnterLoginName(userId);
        if(!ObjectUtils.isEmpty(enterprise)){
            if(!ObjectUtils.isEmpty(id)) {
                LinShare existLinShare = linShareRepository.findLinShareById(id);
                if (!ObjectUtils.isEmpty(existLinShare)) {
                    linShareRepository.updateLinShare(title, content, imgUrl,upimg,downimg,bgcolor,sharetype, url, id);
                }
            }else {
                LinShare linShare = new LinShare();
                linShare.setCompanyId(enterprise.getId());
                linShare.setContent(content);
                linShare.setUrl(url);
                linShare.setImgUrl(imgUrl);
                linShare.setType(sharetype);
                linShare.setTitle(title);
                linShare.setTopimg(upimg);
                linShare.setBottomimg(downimg);
                linShare.setBackgroud(bgcolor);
                linShare.setTime(new Date());
                linShareRepository.save(linShare);
            }
            response.setCode("0");
            response.setMsg("添加分享成功");
        }else{
            response.setCode("200");
            response.setMsg("添加分享失败");
        }
        return response;
    }

    @PostMapping("/api/deleteLinShare")
    @ResponseBody
    public Object deleteLinShareContent(Integer id){
        BaseJsonResponse response = new BaseJsonResponse();
        linShareRepository.deleteById(id);
        response.setMsg("删除成功");
        response.setCode("0");
        return response;
    }

    @PostMapping("/api/add_whole_design_case")
    @ResponseBody
    public Object addWholeDesignCase(String userId,String title,String subtitle,String content,String style,String mainimg){
        BaseJsonResponse response = new BaseJsonResponse();
        Enterprise enterprise = enterpriseRepository.findEnterpriseByEnterLoginName(userId);
        if(!ObjectUtils.isEmpty(enterprise)){
            DesignCase designCase = new DesignCase();
            designCase.setCompanyId(enterprise.getId());
            designCase.setAddtime(new Date());
            designCase.setContent(content);
            designCase.setTitle(title);
            designCase.setSubtitle(subtitle);
            designCase.setImage(mainimg);
            designCase.setStyle(style);
            designCaseRepository.save(designCase);
            response.setCode("0").setMsg("添加整装设计案例成功");
        }
        return response;
    }

    @PostMapping("/api/edit_whole_design_case")
    @ResponseBody
    public Object editWholeDesignCase(Integer id,String title,String subtitle,String content,String style,String mainimg){
        BaseJsonResponse response = new BaseJsonResponse();
            DesignCase designCase = designCaseRepository.findDesignCaseById(id);
            if(!ObjectUtils.isEmpty(designCase)) {
                try {
                    designCaseRepository.updateDesignCase(title, subtitle, content, style, mainimg, id);
                    response.setCode("0").setMsg("修改成功");
                }catch (Exception e){
                    response.setCode("1").setMsg("修改失败");
                }
            }else{
                response.setMsg("修改失败").setCode("1");
            }
        return response;
    }

    @PostMapping("/api/get_whole_design_case_list")
    @ResponseBody
    @CrossOrigin
    public Object getWholeDesignCaseList(String user_id,String token,Integer page,Integer limit) throws ParseException, AlipayApiException {
        BaseJsonResponse response = new BaseJsonResponse();
        verifyUser(user_id, token, response, o -> {
            Agent agent = (Agent) o;
            List<DesignCase> designCaseList =  designCaseRepository.findDesignCasesByCompanyId(agent.getCompanyId(),(page-1)*limit,limit);
            if(designCaseList.size() > 0){
                response.setCode("1").setData(designCaseList).setMsg("获取整装设计列表成功");
            }else{
                response.setCode("1").setData(new ArrayList<>());
            }

        });

        return response;
    }


    /**
     * 获取分享类型接口
     * @param user_id
     * @param token
     * @return
     * @throws ParseException
     * @throws AlipayApiException
     */
    @GetMapping("/api/get_share_type")
    @ResponseBody

    public Object getShareType(String user_id,String token) throws ParseException, AlipayApiException {
        BaseJsonResponse response = new BaseJsonResponse();
        verifyUser(user_id, token, response, o -> {
            Agent agent = (Agent) o;
            List<ShareType> shareTypeList =  shareTypeRepository.findShareTypesByCompanyIdOrderBySort(agent.getCompanyId());
            if(shareTypeList.size() > 0){
                List<ShareTypeData> dataList = new ArrayList<>();
                for(ShareType shareType:shareTypeList){
                    ShareTypeData data = new ShareTypeData();
                    data.setId(shareType.getId());
                    data.setImage_url("/images/"+shareType.getImgUrl());
                    dataList.add(data);
                }
                response.setCode("1").setData(dataList).setMsg("获取整装设计列表成功");
            }
            response.setCode("1").setData(new ArrayList<>());
        });

        return response;
    }


    @GetMapping("/back/get_whole_design_case_list")
    @ResponseBody
    public Object DesignCaseList(String user_id,Integer page,Integer limit){
        DesignCaseResp response = new DesignCaseResp();
        Enterprise enterprise = enterpriseRepository.findEnterpriseByEnterLoginName(user_id);
        if(!ObjectUtils.isEmpty(enterprise)){
            List<DesignCase> designCaseList = designCaseRepository.findDesignCasesByCompanyId(enterprise.getId(),(page-1)*limit,limit);
            if(designCaseList.size() > 0){
                response.setCode(0);
                response.setCount(String.valueOf(designCaseList.size()));
                List<DesignCaseResp.DataBean> dataBeanList = new ArrayList<>();
                for(DesignCase designCase :designCaseList){
                    DesignCaseResp.DataBean dataBean = new DesignCaseResp.DataBean();
                    dataBean.setTitle(designCase.getTitle());
                    dataBean.setSubtitle(designCase.getSubtitle());
                    dataBean.setContext(designCase.getContent());
                    dataBean.setId(designCase.getId());
                    dataBeanList.add(dataBean);
                }
                response.setData(dataBeanList);
                response.setMsg("");
            }else{
                response.setMsg("");
                response.setCode(0);
                response.setData(new ArrayList<>());
                response.setCount("0");
            }
        }
        return response;
    }


    @PostMapping("/back/delete_whole_design_case")
    @ResponseBody
    @CrossOrigin
    public Object deleteWholeDesignCase(Integer id){
        BaseJsonResponse response = new BaseJsonResponse();
        try {
            designCaseRepository.deleteById(id);
            response.setCode("0").setMsg("删除成功");
        }catch (Exception e){
            response.setCode("1").setMsg("删除失败");
        }

        return response;
    }


    @PostMapping("/api/get_whole_design_case_detail")
    @ResponseBody
    @CrossOrigin
    public Object getWholeDesignCaseDetail(Integer id,String user_id,String token) throws ParseException, AlipayApiException {
        BaseJsonResponse response = new BaseJsonResponse();

        verifyUser(user_id, token, response, o -> {
            Agent agent = (Agent) o;
            DesignCase designCase = designCaseRepository.findDesignCaseById(id);
            if(!ObjectUtils.isEmpty(designCase)){
                WholeDesignDetailData data = new WholeDesignDetailData();
                data.setCompanyId(designCase.getCompanyId());
                data.setContent(designCase.getContent());
                data.setImage(designCase.getImage());
                data.setStyle(designCase.getStyle());
                data.setTitle(designCase.getTitle());
                data.setSubtitle(designCase.getSubtitle());
                data.setUrl(Constant.URL + "designcase#/pages/index/al_detail"+"?userId="+agent.getId()+"&companyId="+agent.getCompanyId()+"&id="+id);
                response.setData(data).setCode("1").setMsg("获取详情成功");
            }else{
                response.setMsg("没有详情").setCode("200");
            }
        });

        return response;
    }

    @PostMapping("/back/get_whole_design_case_detail")
    @ResponseBody
    @CrossOrigin
    public Object getWholeDesignCaseDetail(Integer id) throws ParseException, AlipayApiException {
        BaseJsonResponse response = new BaseJsonResponse();


            DesignCase designCase = designCaseRepository.findDesignCaseById(id);
            if(!ObjectUtils.isEmpty(designCase)){
                WholeDesignDetailData data = new WholeDesignDetailData();
                data.setCompanyId(designCase.getCompanyId());
                data.setContent(designCase.getContent());
                data.setImage(designCase.getImage());
                data.setStyle(designCase.getStyle());
                data.setTitle(designCase.getTitle());
                data.setSubtitle(designCase.getSubtitle());
                response.setData(data).setCode("1").setMsg("获取详情成功");
            }else{
                response.setMsg("没有详情").setCode("200");
            }
        return response;
    }



    /**
     * 0元设计
     * @param company_id
     * @param user_id
     * @param city
     * @param name
     * @param phone
     * @return
     */
    @PostMapping("/api/westinghouse")
    @ResponseBody
    @CrossOrigin
    public Object westingHouse(Integer company_id,Integer user_id,String city,String name,String phone){
        BaseJsonResponse response = new BaseJsonResponse();
        WestingHouse westingHouse = new WestingHouse();
        westingHouse.setCity(city);
        westingHouse.setCompanyId(company_id);
        westingHouse.setUserId(user_id);
        westingHouse.setName(name);
        westingHouse.setPhone(phone);
        westingHouse.setTime(new Date());
        try {
            westingHouseRepository.save(westingHouse);
            response.setCode("1");
            response.setMsg("邀请成功");
        }catch (Exception e){
            response.setCode("200").setMsg("邀请失败");
            e.printStackTrace();
        }

        return response;
    }

    /**
     * 房屋估价
     * @param company_id
     * @param user_id
     * @param area
     * @param city
     * @param uname
     * @param phone
     * @param shi
     * @param ting
     * @param wei
     * @param chu
     * @return
     */
    @PostMapping("/api/warehouses")
    @ResponseBody
    @CrossOrigin
    public Object wareHouses(Integer company_id,Integer user_id,Double area,String city,String uname,String phone,String shi,String ting,String wei,String chu){
        BaseJsonResponse response = new BaseJsonResponse();
        WareHouses wareHouses = new WareHouses();
        wareHouses.setCompanyId(company_id);
        wareHouses.setUserId(user_id);
        wareHouses.setArea(area);
        wareHouses.setCity(city);
        wareHouses.setUname(uname);
        wareHouses.setPhone(phone);
        wareHouses.setTime(new Date());
        wareHouses.setHouseType(shi+ting+wei+chu);
        wareHouses.setNum(46465);
        try {
            wareHousesRepository.save(wareHouses);
            response.setCode("1").setMsg("邀请成功");
        }catch (Exception e){
            response.setCode("0").setMsg("邀请失败");
        }

        return response;
    }


    /**
     * 样板房免费接驾到店
     * @param company_id
     * @param user_id
     * @param city
     * @param name
     * @param phone
     * @return
     */
    @PostMapping("/api/roompolys")
    @ResponseBody
    @CrossOrigin
    public Object roompolys(Integer company_id,Integer user_id,String city,String name,String phone){
        BaseJsonResponse response = new BaseJsonResponse();
        RoomPolys roomPolys = new RoomPolys();
        roomPolys.setCity(city);
        roomPolys.setCompanyId(company_id);
        roomPolys.setUserId(user_id);
        roomPolys.setName(name);
        roomPolys.setPhone(phone);
        roomPolys.setTime(new Date());
        try {
            roomPolysRepository.save(roomPolys);
            response.setCode("1");
            response.setMsg("邀请成功");
        }catch (Exception e){
            response.setCode("200").setMsg("邀请失败");
            e.printStackTrace();
        }

        return response;
    }



    /**
     * 验证用户权限
     *
     * @param user_id
     * @param token
     * @param response
     * @param demand
     */
    private void verifyUser(String user_id, String token, BaseJsonResponse response, IDemand demand) throws ParseException, AlipayApiException {
        if (ObjectUtils.isNotEmpty(user_id)) {
            DefaultEnter defaultEnter = defaultEnterRepository.findDefaultEnterByUserIdOrUserTelphone(user_id, user_id);
            if (ObjectUtils.isNotNull(defaultEnter)) {
                Agent agent = agentRepository.findAgentByTelphoneAndCompanyIdOrLoginUsernameAndCompanyId(user_id, defaultEnter.getCompayId(), user_id, defaultEnter.getCompayId());
                if (agent != null) {
                    if (ObjectUtils.isNotEmpty(token) && token.equals(agent.getAccessToken())) {
                        demand.bussiness(agent);
                    } else {
                        response.setMsg("Token过期").setCode("500");
                    }
                } else {
                    response.setCode("500").setMsg("用户不存在");
                }

            } else {
                response.setCode("100").setMsg("用户没有默认公司");
            }
        } else {
            response.setMsg("用户不存在").setCode("100");
        }
    }
}
